package sse.ustc.cc.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class SchoolInfoParser {

	private static String schoolInfoURL = "http://api.map.baidu.com/place/search?&query=%E5%A4%A7%E5%AD%A6";
	private static final String key = "w4CEQvP0bLZOdtLi0BIe2UBU";
	private static double radius = 5000;
	/**
	 * 
	 * @param is
	 * 
	 * @return updateinfo
	 */
	public static ArrayList<AroundSchool> getUpdataInfo(double lat, double lng) {
		
		ArrayList<AroundSchool> aroundSchoolList = null;
		try {
			InputStream is = getInputStream(lat, lng);
			aroundSchoolList = null;
			AroundSchool aroundSchool = null;
			XmlPullParser parser = XmlPullParserFactory.newInstance()
					.newPullParser();
			parser.setInput(is, "utf-8");
			int type = parser.getEventType();

			while (type != XmlPullParser.END_DOCUMENT) {
				String nodeName=parser.getName();
				switch (type) {
				case XmlPullParser.START_DOCUMENT:
					aroundSchoolList = new ArrayList<AroundSchool>();
					break;
				case XmlPullParser.START_TAG:
					if ("result".equals(nodeName)) {
						aroundSchool = new AroundSchool();
					}else if("name".equals(nodeName)){
						aroundSchool.setSchoolName(parser.nextText());
					}else if("address".equals(nodeName)){
						aroundSchool.setSchoolAdd(parser.nextText());
					}
					break;
					//结束节点
			    case XmlPullParser.END_TAG:
			        if("result".equals(nodeName)){
			        	aroundSchoolList.add(aroundSchool);
			        	aroundSchool=null;
			        }
			        break;
				default:
					break;
				}

				type = parser.next();
			}
			is.close();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return aroundSchoolList;
	}

	private static InputStream getInputStream(double lat, double lng) throws Exception {
		
		String path = schoolInfoURL + "&" + "location=" + lat + "," + lng + "&"
				+ "radius=" + radius + "&" + "output=xml&" + "key=" + key;
		
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(2000);
		
		InputStream is = conn.getInputStream();
		if(conn.getResponseCode() == 200){
			System.out.println("chenggong");
		}
		return is;
	}

}
